package com.skyworthclub.competition.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.skyworthclub.competition.beans.Match;
import com.skyworthclub.competition.mapper.MatchMapper;
import com.skyworthclub.competition.service.MatchElasticsearchService;
import com.skyworthclub.competition.service.MatchService;
import com.skyworthclub.competition.utils.service.EmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.Collections;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author li
 * @since 2018-10-15
 * 开启缓存 @CacheConfig
 * 开启异步任务 @EnableAsync
 */
@CacheConfig(cacheNames = "Match")
@EnableAsync
@Service
public class MatchServiceImpl extends ServiceImpl<MatchMapper, Match> implements MatchService {
    /**
     * 单页的元素个数
     */
    private static final int PAGE_SIZE = 5;

    private final MatchElasticsearchService matchElasticsearchService;

    private final EmailService emailService;

    @Autowired
    public MatchServiceImpl(MatchElasticsearchService matchElasticsearchService, EmailService emailService) {
        this.matchElasticsearchService = matchElasticsearchService;
        this.emailService = emailService;
    }


    @Override
    public Page<Match> getPage(Integer pageNum) {
        //构建page对象
        Page<Match> page = new Page<>(pageNum, PAGE_SIZE);
        EntityWrapper<Match> wrapper = new EntityWrapper<>();
        //指定查询字段
        wrapper.setSqlSelect("match_id", "match_name", "match_signup_end", "match_begin_time", "match_image_url", "match_summary");
        //只查询审核通过的
        wrapper.eq("is_checked", 1);
        //按照比赛开始时间排序
        wrapper.orderBy("match_signup_end");
        return super.selectPage(page, wrapper);
    }

    @Override
    public Page<Match> getPubCompetition(String username, Integer pageNum) {
        EntityWrapper<Match> wrapper = new EntityWrapper<>();
        wrapper.eq("match_publisher", username);
        wrapper.setSqlSelect("match_id", "match_name", "match_signup_end", "match_begin_time", "match_image_url", "match_summary");
        wrapper.orderBy("match_id", false);

        Page<Match> page = new Page<>(pageNum, PAGE_SIZE);
        return super.selectPage(page, wrapper);
    }

    @Override
    @Cacheable(keyGenerator = "matchKeyGenerator")
    public Match selectOne(Integer matchId) {
        EntityWrapper<Match> wrapper = new EntityWrapper<>();
        return super.selectOne(wrapper.eq("match_id", matchId));
    }

    /**
     * @param match 存入数据库和es
     *              暂不缓存
     */
    @Override
    public boolean insertOne(Match match) {
        boolean insert = super.insert(match);
        if (insert) {
            //邮件通知管理员审核
            emailService.checkingNotice(match.getMatchName(), 1);
        }
        return insert;
    }

    /**
     * 更新数据库和es
     */
    @Override
    @CacheEvict(keyGenerator = "matchKeyGenerator")
    public boolean updateMatchById(Match match) {
        //编辑过后设为未审核状态
        match.setIsChecked((short) 0);
        boolean update = super.updateById(match);
        if (update) {
            //邮件通知管理员审核
            emailService.checkingNotice(match.getMatchId() + "", 0);
        }
        return update;
    }

    @Override
    @CacheEvict(keyGenerator = "matchKeyGenerator")
    public boolean updateCheckedStatus(Match match, Wrapper<Match> wrapper) {
        return super.update(match, wrapper);
    }

    /**
     * 删除数据库记录和es对应的文档
     */
    @Override
    @CacheEvict(keyGenerator = "matchKeyGenerator")
    public boolean deleteById(Integer matchId, String username) {
        //验证用户
        Match match = super.selectById(matchId);
        if (match == null || !match.getMatchPublisher().equals(username)) {
            return false;
        }
        boolean delete = super.deleteById(matchId);
        if (delete) {
            matchElasticsearchService.delete(matchId);
        }
        return delete;
    }

    /**
     * 查询轮播图信息
     */
    @Override
    public List<Match> selectCarouselFigure() {
        EntityWrapper<Match> wrapper = new EntityWrapper<>();
        wrapper.setSqlSelect("match_id", "match_name", "match_image_url");
        wrapper.eq("is_checked", 1);
        wrapper.orderAsc(Collections.singletonList("last_modify"));
        Page<Match> page = new Page<>(0, PAGE_SIZE);
        page = super.selectPage(page, wrapper);
        return page.getRecords();
    }

    @Override
    public Page<Match> searchByRange(LocalDate startDate, LocalDate endDate, Integer page) {
        EntityWrapper<Match> wrapper = new EntityWrapper<>();
        wrapper.ge("match_signup_end", startDate);
        if (endDate != null) {
            wrapper.and().le("match_signup_end", endDate);
        }
        Page<Match> matchPage = new Page<>(page, PAGE_SIZE);
        return super.selectPage(matchPage, wrapper);
    }

    @Override
    public Page<Match> getPageByMatchIds(List<Integer> matchIds, int pageNum) {
        if (matchIds.size()==0) return null;

        EntityWrapper<Match> wrapper = new EntityWrapper<>();
        wrapper.setSqlSelect("match_id", "match_name", "match_signup_end", "match_begin_time", "match_image_url", "match_summary","match_type","match_level");
        wrapper.in("match_id", matchIds);
        wrapper.orderBy("match_signup_end");
        Page<Match> page = new Page<>(pageNum, PAGE_SIZE);
        return super.selectPage(page, wrapper);
    }

    @Override
    public Page<Match> getPageByType(Integer pageNum, Integer matchType) {
        //构建page对象
        Page<Match> page = new Page<>(pageNum, PAGE_SIZE);
        EntityWrapper<Match> wrapper = new EntityWrapper<>();
        //指定查询字段
        wrapper.setSqlSelect("match_id", "match_name", "match_signup_end", "match_begin_time", "match_image_url", "match_summary","match_type","match_level");
        //只查询审核通过的
        wrapper.eq("is_checked", 1);
        //按类型查询
        wrapper.eq("match_type",matchType);
        //按照比赛开始时间排序
        wrapper.orderBy("match_signup_end");
        return super.selectPage(page, wrapper);
    }

    @Override
    public Page<Match> getPageByLevel(Integer pageNum, Integer matchLevel) {
        //构建page对象
        Page<Match> page = new Page<>(pageNum, PAGE_SIZE);
        EntityWrapper<Match> wrapper = new EntityWrapper<>();
        //指定查询字段
        wrapper.setSqlSelect("match_id", "match_name", "match_signup_end", "match_begin_time", "match_image_url", "match_summary","match_type","match_level");
        //只查询审核通过的
        wrapper.eq("is_checked", 1);
        //按类型查询
        wrapper.eq("match_level",matchLevel);
        //按照比赛开始时间排序
        wrapper.orderBy("match_signup_end");
        return super.selectPage(page, wrapper);
    }


}
